<template>
  <q-page class="q-pa-md">
    <div class="q-pb-md text-h5">{{ pageTitle }}</div>
    <q-space></q-space>
    <div class="shadow-2 q-mb-sm">
      <div class="q-pa-sm">
        <q-btn :disable="loadingState" :loading="loadingState" @click="loadListData" color="primary" dense
          icon="refresh" outline title="刷新" />
      </div>
    </div>
    <div class="shadow-2 q-mt-md">
      <q-table @request="fpsAssist.onDataTableRequest" :rows="$d.tableData" :columns="fpsInfo.columnsInfo"
        separator="cell" row-key="id" v-model:pagination="fpsInfo.paginationInfo"
        :visible-columns="fpsInfo.visibleColumns" dense flat :hide-pagination="true"
        :loading="loadingState" color="primary" binary-state-sort
        hide-selected-banner>
        <template v-slot:top="props">
          <!--填充所有剩余空间-->
          <div class="q-gutter-sm">
            <q-btn color="primary" label="新增" @click="onAddEmailClick"/>
          </div>
          <q-space />
          <q-btn flat dense :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
            :title="props.inFullscreen ? '退出全屏' : '全屏显示'" @click="props.toggleFullscreen" class="q-ml-sm"
            :ripple="false" />
        </template>
        <!--操作列插槽-->
        <template v-slot:body-cell-operation="props">
          <q-td :props="props" auto-width>
            <q-btn color="primary" label="编辑" class="q-mr-xs btn-in-row" dense
              @click="onRowEditClick(props.row)"/>
          </q-td>
        </template>
        <template v-slot:no-data>
          <div class="full-width items-center justify-center row">
            <q-icon name="error_outline" />
            无数据
            <q-btn flat icon="refresh" :loading="loadingState"
              :disable="loadingState" dense title="刷新" size="sm" class="q-ml-sm"
              @click="loadListData"></q-btn>
          </div>
        </template>
      </q-table>
    </div>
    <q-dialog transition-hide="none" transition-show="none" v-model="showingAddEmailCfgDlg">
      <q-card style="max-width: 450px; width: 100%;">
        <q-card-section class="q-pa-sm">
          <div class="text-h6">{{$d.dlgType==='create'?'增加邮件提醒设置':'编辑邮件提醒设置'}}</div>
        </q-card-section>
        <q-separator />
        <!--错误提示-->
        <q-banner class="text-white bg-red" dense inline-actions v-if="serverErrorMessage">
          {{ serverErrorMessage }}
          <template v-slot:action>
            <q-btn @click="serverErrorMessage = ''" dense flat icon="close" size="sm" />
          </template>
        </q-banner>
        <q-card-section class="q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <q-icon color="red" name="fas fa-asterisk" />
              <span>接口名称</span>
              <simple-filter-select :options="apiDropdown" v-model="$d.emailCfgInfo.portTypeSub"
                :readonly="addEmailCfgState || $d.dlgType==='edit'" :option-disable="(i) => optionDisabled(i)"
                :error-message="e$(v$.portTypeSub.$errors)" :error="v$.portTypeSub.$error"/>
            </div>
          </div>
          <div class="row q-col-gutter-sm q-pt-sm">
            <div class="col-12">
              <q-icon color="red" name="fas fa-asterisk" />
              <span>通知邮箱</span>
              <q-icon name="fas fa-info" class="q-mb-xs" color="info">
                <q-tooltip transition-show="none" transition-hide="none" anchor="center right" self="center left">
                  多个邮箱使用英文逗号(,)分隔
                </q-tooltip>
              </q-icon>
              <easy-input v-model="$d.emailCfgInfo.emailTo" :maxlength="1000" :error-message="e$(v$.emailTo.$errors)"
                :error="v$.emailTo.$error" type="textarea" :rows="3"/>
            </div>
          </div>
          <div class="row q-col-gutter-sm q-pt-sm">
            <div class="col-12">
              <span>通知抄送邮箱</span>
              <q-icon name="fas fa-info" class="q-mb-xs" color="info">
                <q-tooltip transition-show="none" transition-hide="none" anchor="center right" self="center left">
                  多个邮箱使用英文逗号(,)分隔
                </q-tooltip>
              </q-icon>
              <easy-input v-model="$d.emailCfgInfo.emailCc" :maxlength="1000" :error-message="e$(v$.emailCc.$errors)"
                :error="v$.emailCc.$error" type="textarea" :rows="3"/>
            </div>
          </div>
        </q-card-section>
        <q-separator class="separator" />
        <q-card-actions align="right">
          <q-btn color="primary" label="确定" @click="doAddEmailCfg"
            :loading="addEmailCfgState"/>
          <q-btn color="primary" label="取消" outline unelevated v-close-popup/>
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'SapEmailCfg'
}
</script>

<script lang="ts" setup>

import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import {computed, reactive, ref} from 'vue'
import {EmailInfo, GetEmailListReq, GetEmailListResp} from 'src/defs/sap/sapEmailCfg'
import {useFpsHelper} from '@njt/foundation/hooks/fpsHelper'
import {ColumnInfo} from '@njt/foundation/defs/comm'
import {useVuelidate} from '@vuelidate/core'
import _ from 'lodash'

const pageTitle = '邮件提醒设置'
useTitleHelper(pageTitle)

let loadingState = ref(false)

const $d = reactive({
  tableData: [] as EmailInfo[],
  dlgType: 'create',
  id: null as number | null,
  emailCfgInfo: {
    portType: 'SAP',
    portTypeSub: '',
    emailTo: '',
    emailCc: '',
  }
})

const columnsDefine: ColumnInfo[] = [
  {
    label: '操作',
    name: 'operation',
    field: 'operation',
    defOrder: 1,
    defVisible: true,
    align: 'left'
  },
  {
    label: '接口名称',
    name: 'portTypeSub',
    field: 'portTypeSub',
    defOrder: 2,
    defVisible: true,
    align: 'left'
  },
  {
    label: '通知邮箱',
    name: 'emailTo',
    field: 'emailTo',
    defOrder: 3,
    defVisible: true,
    align: 'left'
  },
  {
    label: '通知抄送邮箱',
    name: 'emailCc',
    field: 'emailCc',
    defOrder: 4,
    defVisible: true,
    align: 'left'
  },
  {
    label: '创建时间',
    name: 'createDt',
    field: 'createDt',
    defOrder: 5,
    defVisible: true,
    align: 'left',
    format: (val: string) => $f.fmt.dtFmtDateOnly(val)
  },
  {
    label: '创建人',
    name: 'createP',
    field: 'createP',
    defOrder: 6,
    defVisible: true,
    align: 'left',
    format: (val: string, row: EmailInfo) => $f.fmt.userDisp(val, row.createPn)
  },
  {
    label: '更新时间',
    name: 'updateDt',
    field: 'updateDt',
    defOrder: 7,
    defVisible: true,
    align: 'left',
    format: (val: string) => $f.fmt.dtFmtDateOnly(val)
  },
  {
    label: '更新人',
    name: 'updateP',
    field: 'updateP',
    defOrder: 8,
    defVisible: true,
    align: 'left',
    format: (val: string, row: EmailInfo) => $f.fmt.userDisp(val, row.updatePn)
  },
]

let fpsReq: GetEmailListReq = reactive({
  portType: 'SAP',
  pageSize: 40,
  pageNo: 1,
  orderBy: null,
  isDescending: false
})

let showingAddEmailCfgDlg = ref(false)
let serverErrorMessage = ref('')
let addEmailCfgState = ref(false)
const onAddEmailClick = function () {
  $d.dlgType = 'create'
  showingAddEmailCfgDlg.value = true
  serverErrorMessage.value = ''
  resetEmailInfo()
}

const onRowEditClick = function (row: EmailInfo) {
  $d.id = row.id
  $d.dlgType = 'edit'
  $d.emailCfgInfo = {
    emailCc: row.emailCc,
    emailTo: row.emailTo,
    portTypeSub: row.portTypeSub,
    portType: row.portType
  }
  showingAddEmailCfgDlg.value = true
  serverErrorMessage.value = ''
}

const resetEmailInfo = function () {
  $d.emailCfgInfo = {
    portType: 'SAP',
    portTypeSub: '',
    emailTo: '',
    emailCc: '',
  }
  v$.value.$reset()
}

const rule = {
  emailTo: {
    required: $f.validators.required,
    alwaysRight: $f.validators.alwaysRight
  },
  portTypeSub: {
    required: $f.validators.required
  },
  emailCc: {
    alwaysRight: $f.validators.alwaysRight
  }
}
const externalRes = reactive({
  emailTo: '',
  emailCc: ''
})

const v$ = useVuelidate(rule, computed(() => $d.emailCfgInfo), {$autoDirty: true, $scope: false, $externalResults: externalRes})

const doAddEmailCfg = function () {
  const emailArr = _.split($d.emailCfgInfo.emailTo, ',')
  _.forEach(emailArr, (o) => {
    if (!$f.validators.email.$validator(o)) {
      externalRes.emailTo = '邮箱格式不正确'
    }
  })
  const emailCCArr = _.split($d.emailCfgInfo.emailCc, ',')
  _.forEach(emailCCArr, (o) => {
    if (!$f.validators.email.$validator(o)) {
      externalRes.emailCc = '邮箱格式不正确'
    }
  })
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        addEmailCfgState.value = true
        if ($d.dlgType==='create') {
          $f.axios
            .post('/mhlbc/email/create-email', $d.emailCfgInfo)
            .then(() => {
              showingAddEmailCfgDlg.value = false
              loadListData()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              addEmailCfgState.value = false
            })
        } else {
          let formParam = _.cloneDeep($d.emailCfgInfo)
          formParam['id'] = $d.id
          $f.axios
            .post('/mhlbc/email/update-email', formParam)
            .then(() => {
              showingAddEmailCfgDlg.value = false
              loadListData()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              addEmailCfgState.value = false
            })
        }
      }
    })
}

const loadListData = function () {
  serverErrorMessage.value = ''
  loadingState.value = true
  $f.axios
    .get<GetEmailListResp>('/mhlbc/email/get-email-list', {params: fpsReq})
    .then((resp) => {
      $d.tableData = resp.data.emailInfos
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingState.value = false
    })
}

const apiDropdown = [
  'STO GI',
  'GR',
  'IBD GR',
  'GC',
  'IBD GC',
  'OBD PGI',
  'Inventory Adjustment',
  'Pick/Pack',
  'Stock Snapshot'
]

const optionDisabled = computed(() => (i: string) => {
  return _.filter($d.tableData, (o) => o.portTypeSub === i).length!==0
})

const {
  fpsInfo,
  fpsAssist
} = useFpsHelper('/sap/email-cfg',
  null,
  null,
  null,
  fpsReq, columnsDefine,
  null,
  loadListData
)

const e$ = $f.getFieldErrStr
</script>

<style scoped>

</style>